<template>
  <div class="table-list">
    <!-- 添加/编辑表对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加监控表' : '编辑监控表'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="tableForm"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="表名" prop="table_name">
          <el-input v-model="tableForm.table_name" placeholder="请输入表名" />
        </el-form-item>
        <el-form-item label="数据库" prop="database_name">
          <el-input v-model="tableForm.database_name" placeholder="请输入数据库名" />
        </el-form-item>
        <el-form-item label="数据层" prop="layer">
          <el-select v-model="tableForm.layer" placeholder="请选择数据层" style="width: 100%">
            <el-option label="TDS" value="TDS" />
            <el-option label="ODS" value="ODS" />
            <el-option label="DWD" value="DWD" />
            <el-option label="DWS" value="DWS" />
            <el-option label="DIM" value="DIM" />
            <el-option label="ADS" value="ADS" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="tableForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入表描述"
          />
        </el-form-item>
        <el-form-item label="监控间隔(秒)" prop="monitor_interval">
          <el-input-number
            v-model="tableForm.monitor_interval"
            :min="60"
            :max="3600"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="告警阈值" prop="alert_threshold">
          <el-input-number
            v-model="tableForm.alert_threshold"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态" prop="is_active">
          <el-switch v-model="tableForm.is_active" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-card>
      <!-- 搜索和筛选 -->
      <div class="filter-section">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input
              v-model="filters.search"
              placeholder="搜索表名或描述"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="3">
            <el-select v-model="filters.layer" placeholder="数据层" clearable @change="handleFilter">
              <el-option label="全部" value="" />
              <el-option label="TDS" value="TDS" />
              <el-option label="ODS" value="ODS" />
              <el-option label="DWD" value="DWD" />
              <el-option label="DWS" value="DWS" />
              <el-option label="DIM" value="DIM" />
              <el-option label="ADS" value="ADS" />
            </el-select>
          </el-col>
          <el-col :span="3">
            <el-select v-model="filters.status" placeholder="监控状态" clearable @change="handleFilter">
              <el-option label="全部" value="" />
              <el-option label="启用" value="true" />
              <el-option label="禁用" value="false" />
            </el-select>
          </el-col>
          <el-col :span="3">
            <el-select v-model="filters.database" placeholder="数据库" clearable @change="handleFilter">
              <el-option label="全部" value="" />
              <el-option label="test_db" value="test_db" />
              <el-option label="prod_db" value="prod_db" />
            </el-select>
          </el-col>
          <el-col :span="3">
            <el-select v-model="filters.is_monitored" placeholder="是否监控" clearable @change="handleFilter">
              <el-option label="全部" value="" />
              <el-option label="监控" value="true" />
              <el-option label="不监控" value="false" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="handleFilter">筛选</el-button>
            <el-button @click="clearFilters">清除</el-button>
          </el-col>
        </el-row>
      </div>
      
      <!-- 表格工具栏 -->
      <div class="table-toolbar">
        <div class="left">
          <el-button type="success" size="small" @click="handleBatchEnable">批量启用</el-button>
          <el-button type="warning" size="small" @click="handleBatchDisable">批量禁用</el-button>
          <el-button type="success" plain size="small" @click="handleBatchMonitor(true)">批量监控</el-button>
          <el-button type="warning" plain size="small" @click="handleBatchMonitor(false)">批量不监控</el-button>
        </div>
        <div class="right">
          <el-button type="primary" size="small" @click="showAddDialog">添加监控表</el-button>
          <el-button size="small" @click="refreshTables">刷新</el-button>
          <el-dropdown @command="handleColumnToggle">
            <el-button size="small">
              列设置 <el-icon><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item 
                  v-for="col in availableColumns" 
                  :key="col.prop"
                  :command="col.prop"
                >
                  <el-checkbox 
                    v-model="col.visible" 
                    @change="toggleColumn(col.prop)"
                  >
                    {{ col.label }}
                  </el-checkbox>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      
      <el-table 
        :data="filteredTables" 
        style="width: 100%" 
        v-loading="loading"
        @sort-change="handleSortChange"
        :default-sort="{ prop: 'table_name', order: 'ascending' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column 
          type="selection"
          width="55"
        />
        <el-table-column 
          prop="table_name" 
          label="表名" 
          sortable="custom"
          :show="getColumnVisible('table_name')"
        />
        <el-table-column 
          prop="database_name" 
          label="数据库" 
          sortable="custom"
          :show="getColumnVisible('database_name')"
        />
        <el-table-column 
          prop="layer" 
          label="数据层" 
          sortable="custom"
          :show="getColumnVisible('layer')"
        >
          <template #default="{ row }">
            <el-tag :type="getLayerColor(row.layer)" size="small">
              {{ row.layer }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column 
          prop="description" 
          label="描述" 
          show-overflow-tooltip
          :show="getColumnVisible('description')"
        />
        <el-table-column 
          prop="monitor_interval" 
          label="监控间隔(秒)" 
          sortable="custom"
          :show="getColumnVisible('monitor_interval')"
        />
        <el-table-column 
          prop="alert_threshold" 
          label="告警阈值" 
          sortable="custom"
          :show="getColumnVisible('alert_threshold')"
        />
        <el-table-column 
          prop="is_active" 
          label="状态" 
          sortable="custom"
          :show="getColumnVisible('is_active')"
        >
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'danger'" size="small">
              {{ row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column 
          prop="is_monitored" 
          label="是否监控"
          width="120"
        >
          <template #default="{ row }">
            <el-switch :model-value="row.is_monitored ?? true" @change="(val: boolean) => toggleMonitoring(row, val)" />
          </template>
        </el-table-column>
        <el-table-column 
          prop="created_at" 
          label="创建时间" 
          sortable="custom"
          :show="getColumnVisible('created_at')"
        >
          <template #default="{ row }">
            {{ formatTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <ActionMenu
              :actions="[
                { label: '查看', onClick: () => viewTable(row) },
                { label: '编辑', onClick: () => editTable(row) },
                { label: '删除', onClick: () => deleteTable(row) }
              ]"
              :primary-count="2"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { monitorApi } from '@/api/monitor'
import type { MonitoredTable } from '@/types'
import { Search, ArrowDown } from '@element-plus/icons-vue'
import ActionMenu from '@/components/ActionMenu.vue'

const router = useRouter()
const route = useRoute()

// 响应式数据
const tables = ref<MonitoredTable[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()
const selectedRows = ref<MonitoredTable[]>([])

// 筛选条件
const filters = reactive({
  search: '',
  layer: '',
  status: '',
  database: '',
  is_monitored: ''
})

// 列设置
const availableColumns = ref([
  { prop: 'table_name', label: '表名', visible: true },
  { prop: 'database_name', label: '数据库', visible: true },
  { prop: 'layer', label: '数据层', visible: true },
  { prop: 'description', label: '描述', visible: true },
  { prop: 'monitor_interval', label: '监控间隔', visible: true },
  { prop: 'alert_threshold', label: '告警阈值', visible: true },
  { prop: 'is_active', label: '状态', visible: true },
  { prop: 'is_monitored', label: '是否监控', visible: true },
  { prop: 'created_at', label: '创建时间', visible: false }
])

// 表单数据
const tableForm = ref<Partial<MonitoredTable>>({
  table_name: '',
  database_name: '',
  layer: 'TDS',
  description: '',
  monitor_interval: 300,
  alert_threshold: 1000,
  is_active: true,
  is_monitored: true
})

// 表单验证规则
const formRules: FormRules = {
  table_name: [
    { required: true, message: '请输入表名', trigger: 'blur' }
  ],
  database_name: [
    { required: true, message: '请输入数据库名', trigger: 'blur' }
  ],
  layer: [
    { required: true, message: '请选择数据层', trigger: 'change' }
  ]
}

// 筛选后的表格数据
const filteredTables = computed(() => {
  let result = tables.value
  
  if (filters.search) {
    const searchLower = filters.search.toLowerCase()
    result = result.filter(table => 
      table.table_name?.toLowerCase().includes(searchLower) ||
      table.description?.toLowerCase().includes(searchLower)
    )
  }
  
  if (filters.layer) {
    result = result.filter(table => table.layer === filters.layer)
  }
  
  if (filters.status !== '') {
    const statusBool = filters.status === 'true'
    result = result.filter(table => table.is_active === statusBool)
  }
  
  if (filters.database) {
    result = result.filter(table => table.database_name === filters.database)
  }

  if (filters.is_monitored !== '') {
    const m = filters.is_monitored === 'true'
    result = result.filter(t => !!t.is_monitored === m)
  }
  
  return result
})

// 搜索处理
const handleSearch = () => {
  // 实时搜索，不需要额外处理
}

// 筛选处理
const handleFilter = () => {
  // 筛选逻辑已在计算属性中处理
}

// 清除筛选
const clearFilters = () => {
  filters.search = ''
  filters.layer = ''
  filters.status = ''
  filters.database = ''
  filters.is_monitored = ''
}

// 批量启用
const handleBatchEnable = () => {
  ElMessage.info('批量启用功能开发中...')
}

// 批量禁用
const handleBatchDisable = () => {
  ElMessage.info('批量禁用功能开发中...')
}

// 刷新表格
const refreshTables = () => {
  loadTables()
}

// 列设置
const handleColumnToggle = (prop: string) => {
  // 列切换逻辑
}

const toggleColumn = (prop: string) => {
  // 切换列显示/隐藏
}

// 排序处理
const handleSortChange = ({ prop, order }: { prop: string; order: string }) => {
  // 这里可以实现服务端排序，目前使用前端排序
  if (order === 'ascending') {
    filteredTables.value.sort((a: any, b: any) => {
      if (a[prop] < b[prop]) return -1
      if (a[prop] > b[prop]) return 1
      return 0
    })
  } else if (order === 'descending') {
    filteredTables.value.sort((a: any, b: any) => {
      if (a[prop] > b[prop]) return -1
      if (a[prop] < b[prop]) return 1
      return 0
    })
  }
}

// 获取列显示状态
const getColumnVisible = (prop: string): boolean => {
  const column = availableColumns.value.find(col => col.prop === prop)
  return column ? column.visible : true
}

// 获取数据层颜色
const getLayerColor = (layer: string): string => {
  const colors: Record<string, string> = {
    'TDS': 'success',
    'ODS': 'warning',
    'DWD': 'primary',
    'DWS': 'info',
    'DIM': 'danger',
    'ADS': 'success'
  }
  return colors[layer] || 'info'
}

// 格式化时间
const formatTime = (time: string): string => {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN')
}

const loadTables = async () => {
  loading.value = true
  try {
    const response = await monitorApi.getTables({
      page: 1,
      size: 100,
      search: filters.search || undefined,
      layer: filters.layer || undefined,
      is_monitored: filters.is_monitored === '' ? undefined : filters.is_monitored
    })
    tables.value = (response.data.items || []).map(t => ({
      ...t,
      is_monitored: t.is_monitored ?? true
    })) as MonitoredTable[]
  } catch (error) {
    console.error('Failed to load tables:', error)
    ElMessage.error('加载表列表失败')
  } finally {
    loading.value = false
  }
}

const showAddDialog = () => {
  dialogType.value = 'add'
  tableForm.value = {
    table_name: '',
    database_name: '',
    layer: 'ODS',
    description: '',
    monitor_interval: 300,
    alert_threshold: 1000,
    is_active: true,
    is_monitored: true
  }
  dialogVisible.value = true
}

const editTable = (table: MonitoredTable) => {
  dialogType.value = 'edit'
  tableForm.value = { 
    id: table.id,
    table_name: table.table_name,
    database_name: table.database_name,
    layer: table.layer,
    description: table.description || '',
    monitor_interval: table.monitor_interval,
    alert_threshold: table.alert_threshold,
    is_active: table.is_active,
    is_monitored: table.is_monitored
  }
  dialogVisible.value = true
}

const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (dialogType.value === 'add') {
      await monitorApi.createTable(tableForm.value)
      ElMessage.success('添加成功')
    } else {
      await monitorApi.updateTable(tableForm.value.id!, tableForm.value)
      ElMessage.success('更新成功')
    }
    
    dialogVisible.value = false
    loadTables()
  } catch (error) {
    console.error('Form submission failed:', error)
    ElMessage.error('操作失败')
  }
}

const deleteTable = async (table: MonitoredTable) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除表 "${table.table_name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await monitorApi.deleteTable(table.id)
    ElMessage.success('删除成功')
    loadTables()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Delete failed:', error)
      ElMessage.error('删除失败')
    }
  }
}

const viewTable = (table: MonitoredTable) => {
  router.push(`/monitor/table/${table.id}`)
}

const handleSelectionChange = (rows: MonitoredTable[]) => { selectedRows.value = rows }

const toggleMonitoring = async (row: MonitoredTable, val: boolean) => {
  await monitorApi.toggleTableMonitoring(row.id!, val)
  row.is_monitored = val
}

const handleBatchMonitor = async (isMonitored: boolean) => {
  const ids = selectedRows.value.map(r => r.id!).filter(Boolean)
  if (!ids.length) { ElMessage.info('请先选择要操作的表'); return }
  await monitorApi.batchToggleMonitoring(ids, isMonitored)
  tables.value.forEach(t => { if (ids.includes(t.id!)) t.is_monitored = isMonitored })
  ElMessage.success('已更新监控状态')
}

onMounted(() => {
  loadTables()
  // 从路由参数读取默认筛选条件
  if (route.query.layer) {
    filters.layer = route.query.layer as string
  }
})

// 监听路由变化，当筛选条件改变时重新加载数据
watch(() => route.query, () => {
  loadTables()
}, { deep: true })
</script>

<style scoped>
.table-list {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 12px 0 8px;
}
</style> 